<!DOCTYPE html>
<head>
    <title>socketio 非房间</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
          charset="UTF-8"/>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            text-align: center;
        }

        .btn {
            line-height: 24px;
            text-align: center;
            font-size: 14px;
            border: 1px solid blue;
            background-color: #fff;
            margin-bottom: 20px;
            padding: 0 10px;
        }

        .message {
            position: fixed;
            bottom: 0;
            width: 100%;
            padding: 10px;
            font-size: 14px;
            color: #000;
        }
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/socket.io/3.0.0-rc4/socket.io.js"></script>
    "

</head>
<body>
<div class="box">
    <div class="message" id="message"></div>
    <br/>
    <button class="btn" onclick="wsReq()">connect</button>
    <button class="btn" onclick="echo()">request echo</button>
    <button class="btn" onclick="closews()">close</button>
    <button class="btn" onclick="LogIn()">LogIn</button>

    <br/>
    <p>用户账号</p>
    <input id="userID" type="text" name="fname"/>

    <br/>

    <input id="roomID" type="text" name="fname"/>
    <br/>
    <br/>
    <button class="btn" onclick="loginRoom()">loginRoom</button>
    <button class="btn" onclick="leaveRoom()">leaveRoom</button>
    <button class="btn" onclick="sendRoom()">sendRoom</button>
    <br/>
    <button class="btn" onclick="sendPerson()">sendtoPerson</button>

    <p id="content"></p>
</div>

<script>

/**
导入模块方式
const io = require('socket.io-client');
// or with import syntax
import io from 'socket.io-client';

 直接引用
<script src="/socket.io/socket.io.js"/>
const socket = io('http://localhost');
*/

let connected = false;
let nums = 0;
//建立websocket连接，连接异常断开时，socket.io 会自动重新连接的，如果不希望自动重连，需要捕获异常，然后主动调用disconnect
//transports 如下设置，表示优先使用websocket
const socket = io('ws://192.168.0.101:8092',{
    "transports":['websocket', 'polling']
});

socket.on('echo', msg => {
    console.log('recv info frome server:' + msg);
    document.getElementById("content").innerHTML = msg;
})

socket.on('receiveMessage',msg => {

    console.log('recv info:' + msg);
    document.getElementById("content").innerHTML = msg;
})

socket.on('roomMessage',msg => {
    let rm = msg.roomID + " " + msg.from +" " + msg.data;
    document.getElementById("content").innerHTML = rm;

    console.log('roomMessage:' + rm );
})

//下面为socket.io内置事件
socket.on('connect', function (data) {
    //连接正常的事件
    console.log(JSON.stringify(data) + ' - connect');
    connected = true;
    document.getElementById("content").innerHTML = 'websocket连接成功';
});

socket.on('disconnect', function (data) {
    //失去连接的事件
    console.log(JSON.stringify(data) + ' - disconnect');
    connected = false;
    // //主动关闭，否则会一直重连(如果需要本身就是需要重连，则不需要调用下面关闭代码)
    socket.disconnect();

    document.getElementById("content").innerHTML = 'websocket连接断开';
});

//加上io 才能捕获异常
socket.io.on('connect_error', function (data) {
    console.log(JSON.stringify(data) + ' - connect_error');
});

socket.io.on('connect_timeout', function (data) {
    console.log(JSON.stringify(data) + ' - connect_timeout');
});

socket.io.on('error', function (data) {
    console.log(JSON.stringify(data) + ' - error');
    connected = false;
    socket.disconnect();

    document.getElementById("content").innerHTML = 'websocket连接异常';
});

//下面这些内置事件，测试没有输出
socket.io.on('reconnect', function (data) {
    console.log(JSON.stringify(data) + ' - reconnect');
});
socket.on('reconnect_attempt', function (data) {
    console.log(JSON.stringify(data) + ' - reconnect_attempt');
});
socket.on('reconnecting', function (data) {
    console.log(JSON.stringify(data) + ' - reconnecting');
});
socket.on('reconnect_error', function (data) {
    console.log(JSON.stringify(data) + ' - reconnect_error');
});
socket.on('reconnect_failed', function (data) {
    console.log(JSON.stringify(data) + ' - reconnect_failed');
});
socket.on('ping', function (data) {
    console.log(JSON.stringify(data) + ' - ping');
});
socket.on('pong', function (data) {
    console.log(JSON.stringify(data) + ' - pong');
});

function closews() {

    if (connected) {
        console.log("close");
        connected = false;
        socket.disconnect();
    }
}

function echo() {
    // socket.emit('echo', 'client send to server:' + nums++);

    //发送信息，并接收对方对方回复
    socket.emit('echo-response', "1", {name: "test response"}, (response) => {
        console.log(response.status);
    });
}


function wsReq() {
    if (!connected) {
        socket.connect();
    }
};

function LogIn() {

    let text = document.getElementById("userID");

    socket.emit('LogIn',{userID:text.value});
}

function sendPerson() {

    let text = document.getElementById("roomID");

    socket.emit('sendMessage',{to:text.value,data:'person send to person'});
}

/*
 socket.on('roomMessage',msg => {
        //房间信息，类似聊天时，群组等，具体协议可细分
        io.sockets.in(msg.roomID).emit('roomMessage',msg.data);
    });

    socket.on('loginRoom',msg => {
        //TODO： 根据msg内容加入对应的房间
        wsUsers[msg.userID] = {sockID:socket.id,ws:socket};

        socket.join(msg.roomID);
        console.log(io.sockets.manager.rooms);
    });
* */

function loginRoom() {

    //可以加入多个房间，

    let room = document.getElementById("roomID");
    let user = document.getElementById("userID");

    socket.emit('loginRoom',{roomIDs:[room.value],userID:user.value });
}
function leaveRoom() {

    let room = document.getElementById("roomID");
    let user = document.getElementById("userID");

    socket.emit('leaveRoom',{roomIDs:[room.value],userID:user.value });

}

function sendRoom() {

    let data = 'room message' + nums++;
    let text = document.getElementById("roomID");
    socket.emit('roomMessage',{roomID:text.value,data:data });
}


// console.log(window.location.host);
// console.log(window.location.href);

</script>
</body>
</html>
